package com.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取单例驱动
 */
public class AutoTestUtils {

    private static EdgeDriver driver;

    public static EdgeDriver getDriver() {
        EdgeOptions options = new EdgeOptions();
        options.addArguments("--remote-allow-origins=*");
        if(driver == null) {
            driver = new EdgeDriver(options);
            //创建隐式等待，设置最长等待时间为 10s
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        }
        return driver;
    }

    /**
     * 获取屏幕截图，将用例执行结果保存下来
     * @param str
     */
    public void getScreenShot(String str) throws IOException {
        List<String> list = getTime();
        String fileName = "./src/test/java/com/blogWebAutoTest/" + list.get(0) + "/" + str + "_" + list.get(1) + ".png";
        File srcFile = driver.getScreenshotAs(OutputType.FILE);
        //把生成的截图放入指定路径
        FileUtils.copyFile(srcFile, new File(fileName));
    }

    private List<String> getTime() {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        //保存的文件夹名：当天的年月 +  具体时间
        String fileName = sdf1.format(System.currentTimeMillis());
        //保存的图片名：当天年月
        String dirName = sdf2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirName);
        list.add(fileName);
        return list;
    }

}
